package com.eastseeway.radioproject;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.eastseeway.radioproject.base.Const;
import com.eastseeway.radioproject.utils.SPHelper;
import com.eastseeway.radioproject.utils.TimeUtils;

import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

public class OperationHoursService extends Service {

    private InnerBinder mInnerBinder;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mInnerBinder;
    }


    public class InnerBinder extends Binder{

        private TimeChangeObserver mTimeChangeObserver;

        public InnerBinder() {
            startTimer();
        }

        public void addTimeChangeObserver(TimeChangeObserver timeChangeObserver) {
            mTimeChangeObserver = timeChangeObserver;
        }

        private void startTimer(){
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
//                获取之前的累计时间
                    long operationHours = SPHelper.getOperationHours(getBaseContext());
                    operationHours = operationHours + Const.TIME_1_MIN;
                    SPHelper.saveOperationHours(getBaseContext(), operationHours);
                    String diffTime = TimeUtils.getDiffTime(operationHours);
                    if (mTimeChangeObserver != null) {
                        mTimeChangeObserver.onTimeChanged(diffTime);
                    }
                }
            }, 0, 1000 * 60);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mInnerBinder == null) {
            mInnerBinder = new InnerBinder();
        }
    }


}
